/**
 * 
 */
package cn.spadger.aio.chatroom.server;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * @author l5222
 *
 */
public class ReadHandler implements CompletionHandler<Integer, Object> {

	private static ByteBuffer buffer;
	private static AcceptHandler acceptHandler;
	private static AsynchronousSocketChannel socketChannel;

	/**
		* 
		*/
	public ReadHandler(ByteBuffer buffer, AcceptHandler acceptHandler, AsynchronousSocketChannel socketChannel) {
		this.buffer = buffer;
		this.acceptHandler = acceptHandler;
		this.socketChannel = socketChannel;
	}

	@Override
	public void completed(Integer result, Object attachment) {
		buffer.flip();
		try {
			if (result > 0) {
				System.out.print(socketChannel.getRemoteAddress() + ":"
						+ new String(buffer.array(), 0, buffer.remaining(), Server.CHARSET));
				buffer.clear();
				socketChannel.read(buffer, null, this);
			} else if (result < 0) {
				acceptHandler.removeClient(socketChannel);
			}
			if (result < buffer.capacity())
				System.out.println();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public void failed(Throwable exc, Object attachment) {
	}

}
